package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"videos/model/cache"
	"videos/model/mysql"
	"videos/videorpc/internal/svc"
	"videos/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoListLogic {
	return &VideoListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoListLogic) VideoList(in *videorpc.VideoListRequest) (*videorpc.VideoListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*videorpc.VideoList

	key := fmt.Sprintf("videoList_%s", in)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cacheData == "" {
		list = mysql.VideoList(mysql.DB, in)

		jsonData, _ := json.Marshal(list)

		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*10)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	return &videorpc.VideoListResponse{
		List: list,
	}, nil
}
